<!DOCTYPE html>


<html lang="en">
  

    <head>
      <meta charset="utf-8" />
        
      <meta
        name="viewport"
        content="width=device-width, initial-scale=1, maximum-scale=1"
      />
      <title>《JavaScript高级程序设计》- 第十章：函数 |  欢迎</title>
  <meta name="generator" content="hexo-theme-ayer">
      
      <link rel="shortcut icon" href="/favicon.ico" />
       
<link rel="stylesheet" href="/dist/main.css">

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css"
      />
      
<link rel="stylesheet" href="/css/custom.css">
 
      <script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>
       
 

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/@sweetalert2/theme-bulma@5.0.1/bulma.min.css"
      />
      <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.19/dist/sweetalert2.min.js"></script>

      <!-- mermaid -->
      
      <style>
        .swal2-styled.swal2-confirm {
          font-size: 1.6rem;
        }
      </style>
    <link rel="alternate" href="/atom.xml" title="欢迎" type="application/atom+xml">
</head>
  </html>
</html>


<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-JavaScript学习/《JavaScript高级程序设计》- 第十章：函数"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  《JavaScript高级程序设计》- 第十章：函数
</h1>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2022/02/23/JavaScript%E5%AD%A6%E4%B9%A0/%E3%80%8AJavaScript%E9%AB%98%E7%BA%A7%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E3%80%8B-%20%E7%AC%AC%E5%8D%81%E7%AB%A0%EF%BC%9A%E5%87%BD%E6%95%B0/" class="article-date">
  <time datetime="2022-02-23T15:10:35.000Z" itemprop="datePublished">2022-02-23</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/JavaScript%E5%AD%A6%E4%B9%A0/">JavaScript学习</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> Word count:</span>
            <span class="post-count">4.9k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> Reading time≈</span>
            <span class="post-count">21 min</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <h2 id="第十章：函数"><a href="#第十章：函数" class="headerlink" title="第十章：函数"></a>第十章：函数</h2><p>实际上<strong>函数也是对象</strong>，每个函数都是对象<code>Function</code>的实例，其也拥有<strong>属性</strong>和<strong>方法</strong>；</p>
<p>因为函数也是对象，所以<code>函数名</code>则是指向函数对象的<code>指针</code>；</p>
<h3 id="10-1-函数的声明"><a href="#10-1-函数的声明" class="headerlink" title="10.1 函数的声明"></a>10.1 函数的声明</h3><ol>
<li><p>函数声明式</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sum</span>(<span class="params">num1,num2</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> num1+num2;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li><p>函数表达式</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> sum = <span class="function"><span class="keyword">function</span>(<span class="params">num1,num2</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> num1+num2;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li><p>构造函数式：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> sum = <span class="keyword">new</span> <span class="built_in">Function</span>(<span class="string">&#x27;num1&#x27;</span>,<span class="string">&#x27;num2&#x27;</span>,<span class="string">&#x27;return num1+num2&#x27;</span>);</span><br></pre></td></tr></table></figure>

<blockquote>
<p><strong>十分不推荐</strong>这种写法，因为会解释两次，影响性能。</p>
</blockquote>
</li>
<li><p>箭头函数式：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> sum = <span class="function">(<span class="params">num1,num2</span>) =&gt;</span> <span class="keyword">return</span> num1+num2;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>箭头函数有如下特点：</p>
<ul>
<li>如果只有一个参数，可以省略小括号</li>
<li>如果只有一行代码，可以省略大括号</li>
<li>不能使用<code>arguments``super</code>和<code>new.target</code>；也不能使用<code>构造函数</code>、没有<code>prototype</code>属性</li>
<li><code>this</code>指向定义箭头函数时的上下文作用域</li>
</ul>
</blockquote>
</li>
</ol>
<h3 id="10-2-函数名"><a href="#10-2-函数名" class="headerlink" title="10.2 函数名"></a>10.2 函数名</h3><p>因为函数名就是指向函数的指针，所以可以一个函数拥有多个名称；</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sum</span>(<span class="params">num1,num2</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> num1+num2;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> anotherSum = sum;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(sum(<span class="number">10</span>,<span class="number">20</span>));		<span class="comment">// 30</span></span><br><span class="line"><span class="built_in">console</span>.log(anotherSum(<span class="number">10</span>,<span class="number">20</span>));	<span class="comment">// 30</span></span><br></pre></td></tr></table></figure>



<p>在ES6中，所有函数对象都会暴露一个<code>只读的name属性</code>；</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>) </span>&#123;&#125;</span><br><span class="line"><span class="keyword">let</span> bar = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;;</span><br><span class="line"><span class="keyword">let</span> baz = <span class="function">() =&gt;</span> &#123;&#125;;</span><br><span class="line"><span class="keyword">let</span> nav = <span class="keyword">new</span> <span class="built_in">Function</span>();</span><br><span class="line"><span class="built_in">console</span>.log(foo.name); <span class="comment">// foo</span></span><br><span class="line"><span class="built_in">console</span>.log(bar.name); <span class="comment">// bar</span></span><br><span class="line"><span class="built_in">console</span>.log(baz.name); <span class="comment">// baz</span></span><br><span class="line"><span class="built_in">console</span>.log((<span class="function">() =&gt;</span> &#123;&#125;).name); <span class="comment">//（空字符串）</span></span><br><span class="line"><span class="built_in">console</span>.log(nav.name); <span class="comment">// anonymous</span></span><br></pre></td></tr></table></figure>



<h3 id="10-3-函数参数"><a href="#10-3-函数参数" class="headerlink" title="10.3 函数参数"></a>10.3 函数参数</h3><p>与其他语言不一样，<code>ECMAScript</code>函数<strong>不关心</strong>传入参数的个数；不管少传，还是多传，解释器都不会报错。</p>
<p>主要是因为：参数在内部表现为一个<code>数组</code>；<strong>箭头函数除外</strong>，可以在函数内部访问<code>arguments</code>对象，从而<code>获取传参</code>、<code>传参个数</code>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sayHi</span>(<span class="params">name,message</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">`Hi,<span class="subst">$&#123;name&#125;</span>!<span class="subst">$&#123;message&#125;</span>`</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">anotherSayHi</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">`Hi,<span class="subst">$&#123;<span class="built_in">arguments</span>[<span class="number">0</span>]&#125;</span>!<span class="subst">$&#123;<span class="built_in">arguments</span>[<span class="number">1</span>]&#125;</span>`</span>);</span><br><span class="line">&#125;</span><br><span class="line">sayHi(<span class="string">&#x27;zyzc&#x27;</span>,<span class="string">&#x27;welcome&#x27;</span>);		<span class="comment">// Hi，zyzc！welcome</span></span><br><span class="line">anotherSayHi(<span class="string">&#x27;zyzc&#x27;</span>,<span class="string">&#x27;welcome&#x27;</span>);	<span class="comment">// Hi，zyzc！welcome</span></span><br></pre></td></tr></table></figure>

<p>与其他语言不同，<code>ECMASCript</code>函数的参数只是<code>方便调用</code>而命名的，而<code>不是必需的</code>；因为根本不存在<strong>验证命名参数的机制</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getLength</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">arguments</span>.length);</span><br><span class="line">&#125;</span><br><span class="line">getLength();			<span class="comment">// 0</span></span><br><span class="line">getLength(<span class="string">&#x27;zyzc&#x27;</span>,<span class="number">18</span>);	<span class="comment">// 2</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>这里有一个需要注意的地方，arguments对象的值，始终与对应的命名参数同步。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sum</span>(<span class="params">num1,num2</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">arguments</span>[<span class="number">0</span>] = <span class="number">10</span>;</span><br><span class="line">    <span class="built_in">console</span>.log(num1 + num2);</span><br><span class="line">&#125;</span><br><span class="line">sum(<span class="number">20</span>,<span class="number">20</span>);		<span class="comment">// 30</span></span><br></pre></td></tr></table></figure>

<p>但是在<code>严格模式</code>下不会出现这种情况。再者：函数中尝试修改<code>arguments</code>对象会导致语法错误。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&quot;use strict&quot;</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sum</span>(<span class="params">num1,num2</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">arguments</span> = &#123;&#125;;     <span class="comment">// Unexpected eval or arguments in strict mode</span></span><br><span class="line">    <span class="built_in">console</span>.log(num1 + num2);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</blockquote>
<h4 id="10-3-1-箭头函数参数"><a href="#10-3-1-箭头函数参数" class="headerlink" title="10.3.1 箭头函数参数"></a>10.3.1 箭头函数参数</h4><p>传给箭头函数的参数，<strong>不能</strong>使用arguments关键字访问；</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	<span class="built_in">console</span>.log(<span class="built_in">arguments</span>[<span class="number">0</span>]);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> bat = <span class="function">()=&gt;</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">arguments</span>[<span class="number">0</span>]);</span><br><span class="line">&#125;</span><br><span class="line">foo(<span class="number">5</span>);     <span class="comment">// 5</span></span><br><span class="line">bat(<span class="number">5</span>);     <span class="comment">// &#123;&#125;</span></span><br></pre></td></tr></table></figure>

<p>但是可以这样做：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">let</span> bar = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="built_in">arguments</span>[<span class="number">0</span>]);</span><br><span class="line">    &#125;</span><br><span class="line">    bar();</span><br><span class="line">&#125;</span><br><span class="line">foo(<span class="number">5</span>);		<span class="comment">// 5</span></span><br></pre></td></tr></table></figure>



<h3 id="10-4-没有重载机制"><a href="#10-4-没有重载机制" class="headerlink" title="10.4 没有重载机制"></a>10.4 没有重载机制</h3><p>因为ECMAScript函数没有签名，自然也没有重载；</p>
<p>如果存在同名函数，后定义的会<code>覆盖</code>先定义的。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sum</span>(<span class="params">num1</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">100</span> + num1;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sum</span>(<span class="params">num1</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">200</span> + num1;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(sum(<span class="number">100</span>));   <span class="comment">// 300</span></span><br></pre></td></tr></table></figure>



<h3 id="10-5-默认参数值"><a href="#10-5-默认参数值" class="headerlink" title="10.5 默认参数值"></a>10.5 默认参数值</h3><p>在ECMAScript5.1之前，是需要自己手动给默认值的；</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">showKing</span>(<span class="params">name</span>)</span>&#123;</span><br><span class="line">    name = (<span class="keyword">typeof</span> name !== <span class="string">&#x27;undefined&#x27;</span>) ? name : <span class="string">&#x27;defaultName&#x27;</span>;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">`King is <span class="subst">$&#123;name&#125;</span>!`</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(showKing());        <span class="comment">// King is defaultName!</span></span><br><span class="line"><span class="built_in">console</span>.log(showKing(<span class="string">&#x27;zyzc&#x27;</span>));  <span class="comment">// King is zyzc!</span></span><br></pre></td></tr></table></figure>

<p>在ES6后，就不必如此麻烦了</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">showKing</span>(<span class="params">name=<span class="string">&#x27;defaultName&#x27;</span></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">`King is <span class="subst">$&#123;name&#125;</span>!`</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(showKing());        <span class="comment">// King is defaultName!</span></span><br><span class="line"><span class="built_in">console</span>.log(showKing(<span class="string">&#x27;zyzc&#x27;</span>));  <span class="comment">// King is zyzc!</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>当然，默认值除了是<code>原始值</code>之外，还可以是引用值、函数；</p>
</blockquote>
<blockquote>
<p>ES6中，给参数默认值，可以如下理解：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">showKing</span>(<span class="params"></span>)</span>&#123;<span class="comment">// showKing(name=&#x27;defaultName&#x27;,message=&#x27;This is my kingdom!&#x27;)</span></span><br><span class="line">    <span class="keyword">let</span> name = <span class="string">&#x27;defaultName&#x27;</span>;</span><br><span class="line">    <span class="keyword">let</span> message = <span class="string">&#x27;This is my kingdom!&#x27;</span>;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">`King is <span class="subst">$&#123;name&#125;</span>:<span class="subst">$&#123;message&#125;</span>`</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(showKing());        <span class="comment">// King is defaultName:This is my kingdom!</span></span><br></pre></td></tr></table></figure>

<p>显然，这样会出现<code>暂时性死区</code>的现象；即前面定义的参数，不能引用后面定义的参数。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">showKing</span>(<span class="params">name=<span class="string">&#x27;default&#x27;</span>,message=name</span>)</span>&#123;	<span class="comment">// 可行</span></span><br><span class="line">    <span class="keyword">return</span> <span class="string">`King is <span class="subst">$&#123;name&#125;</span>:<span class="subst">$&#123;message&#125;</span>`</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(showKing());        <span class="comment">// King is default:default</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>不能这样使用</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">showKing</span>(<span class="params">name=message,message=<span class="string">&#x27;default&#x27;</span></span>)</span>&#123;	<span class="comment">// 不可行</span></span><br><span class="line">    <span class="keyword">return</span> <span class="string">`King is <span class="subst">$&#123;name&#125;</span>:<span class="subst">$&#123;message&#125;</span>`</span>;</span><br><span class="line">&#125;<span class="comment">//  Cannot access &#x27;message&#x27; before initialization</span></span><br></pre></td></tr></table></figure>
</blockquote>
</blockquote>
<h3 id="10-6-参数扩展与收集"><a href="#10-6-参数扩展与收集" class="headerlink" title="10.6 参数扩展与收集"></a>10.6 参数扩展与收集</h3><h4 id="10-6-1-扩展参数"><a href="#10-6-1-扩展参数" class="headerlink" title="10.6.1 扩展参数"></a>10.6.1 扩展参数</h4><p>扩展运算符<code>...</code>是ES6的语法，用于取出参数对象的所有可遍历属性；</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> values = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>];</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getSum</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">let</span> sum = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">let</span> i=<span class="number">0</span> ; i&lt;<span class="built_in">arguments</span>.length ; i++)&#123;</span><br><span class="line">        sum += <span class="built_in">arguments</span>[i];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> sum;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(getSum(...values));		<span class="comment">// 15</span></span><br><span class="line"><span class="comment">// 扩展运算符还可以与其他参数一起使用</span></span><br><span class="line"><span class="built_in">console</span>.log(getSum(-<span class="number">1</span>,...values));  <span class="comment">// 14</span></span><br><span class="line"><span class="built_in">console</span>.log(getSum(...values,-<span class="number">1</span>));  <span class="comment">// 14</span></span><br><span class="line"><span class="built_in">console</span>.log(getSum(...values,...[<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>,<span class="number">10</span>]));     <span class="comment">// 55</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>探究扩展后到底是怎样的？</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> values = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>];</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getLength</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">arguments</span>.length);</span><br><span class="line">&#125;</span><br><span class="line">getLength(...values);		<span class="comment">// 5</span></span><br><span class="line">getLength(-<span class="number">1</span>,...values);    <span class="comment">// 6</span></span><br><span class="line">getLength(...values,-<span class="number">1</span>);    <span class="comment">// 6</span></span><br><span class="line">getLength(...values,...[<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>,<span class="number">10</span>]);     <span class="comment">// 10</span></span><br></pre></td></tr></table></figure>

<p>按上面结果可知：</p>
<ul>
<li>扩展后的传参为<code>getLength(1,2,3,4,5);</code></li>
<li><code>arguments</code>对象并不知道扩展运算符的存在，只是在消费扩展运算符。</li>
</ul>
</blockquote>
<h4 id="10-6-2-收集剩余参数"><a href="#10-6-2-收集剩余参数" class="headerlink" title="10.6.2 收集剩余参数"></a>10.6.2 收集剩余参数</h4><p>显然，我们可以通过拓展运算符，将传入数组（不局限于数组）的一部分提取出来，另一部分继续放在数组中。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">ignoreFirst</span>(<span class="params">firstValue,...values</span>)</span>&#123;	<span class="comment">// 可行</span></span><br><span class="line">    <span class="built_in">console</span>.log(values);</span><br><span class="line">&#125;</span><br><span class="line">ignoreFirst();  <span class="comment">// []</span></span><br><span class="line">ignoreFirst(<span class="number">1</span>); <span class="comment">// []</span></span><br><span class="line">ignoreFirst(<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>); <span class="comment">// [2,3]</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>注意：不能这样写：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getLast</span>(<span class="params">...values,lastValue</span>)</span>&#123;</span><br><span class="line">    <span class="comment">// 会报错</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</blockquote>
<p>​    </p>
<h4 id="10-6-3-拓展运算符-箭头函数"><a href="#10-6-3-拓展运算符-箭头函数" class="headerlink" title="10.6.3 拓展运算符 + 箭头函数"></a>10.6.3 拓展运算符 + 箭头函数</h4><p>由于箭头函数没有<code>arguments</code>对象，所以很多时候不能对多个传参进行操作；</p>
<p>但是可以使用<code>拓展运算符</code>来解决该问题</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> args = <span class="function">(<span class="params">...values</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(values);	<span class="comment">// 这就相当于arguments</span></span><br><span class="line">    <span class="built_in">console</span>.log(values.length);</span><br><span class="line">&#125;</span><br><span class="line">args(<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>);</span><br></pre></td></tr></table></figure>



<p>​    </p>
<h3 id="10-7-函数声明式和函数表达式"><a href="#10-7-函数声明式和函数表达式" class="headerlink" title="10.7 函数声明式和函数表达式"></a>10.7 函数声明式和函数表达式</h3><p>函数声明式：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sum</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>函数表达式：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> sum = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;	</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="10-7-1-注意"><a href="#10-7-1-注意" class="headerlink" title="10.7.1 注意"></a>10.7.1 注意</h4><blockquote>
<p>两者有什么区别？</p>
<p><strong>函数声明式</strong>具有函数提升效果，而<strong>函数表达式</strong>没有！</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(sum1());	<span class="comment">// 0</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sum1</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(sum2());	<span class="comment">// Cannot access &#x27;sum2&#x27; before initialization</span></span><br><span class="line"><span class="keyword">let</span> sum2 = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;	</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>有没有可能是<code>let</code>的暂时性死区造成的？</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(sum3());    <span class="comment">// TypeError: sum3 is not a function</span></span><br><span class="line"><span class="keyword">var</span> sum3 = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>也是不行！</p>
</blockquote>
<blockquote>
<p>不能这样做：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span>(condition)&#123;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">sayHi</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;hi&#x27;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;<span class="keyword">else</span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">sayHi</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;Yo&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>很多浏览器都会直接忽略第一个条件，直接<strong>返回第二个声明</strong>；火狐浏览器则会在第一个<code>condition</code>为<code>true</code>的时候，<strong>返回第一个声明</strong>;</p>
<p>但是可以使用函数表达式处理！</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> sayHi;</span><br><span class="line"><span class="keyword">if</span>(condition)&#123;</span><br><span class="line">    sayHi = <span class="function"><span class="keyword">function</span> (<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;hi&#x27;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;<span class="keyword">else</span>&#123;</span><br><span class="line">    sayHi = <span class="function"><span class="keyword">function</span> (<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;Yo&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


</blockquote>
<h3 id="10-8-函数作为值"><a href="#10-8-函数作为值" class="headerlink" title="10.8 函数作为值"></a>10.8 函数作为值</h3><p>因为<strong>函数名</strong>在<code>ECMAScript</code>中就是<strong>变量</strong>，所以在可以使用变量的地方使用；</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">callSomeFunction</span>(<span class="params">someFunction,someArguments</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> someFunction(someArguments);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sum</span>(<span class="params">num</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> num+<span class="number">10</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> result = callSomeFunction(sum,<span class="number">10</span>);</span><br><span class="line"><span class="built_in">console</span>.log(result);    <span class="comment">// 20</span></span><br></pre></td></tr></table></figure>





<h3 id="10-9-函数内部"><a href="#10-9-函数内部" class="headerlink" title="10.9 函数内部"></a>10.9 函数内部</h3><p>ES5中，在函数内部存在两个特殊的对象：<code>arguments</code>和<code>this</code>；</p>
<p>ES6中，又新增了<code>new.target</code>属性。</p>
<h4 id="10-9-1-arguments"><a href="#10-9-1-arguments" class="headerlink" title="10.9.1 arguments"></a>10.9.1 arguments</h4><ul>
<li><p>它是一个<code>类数组对象</code>，包含调用函数时传入的所有参数；</p>
</li>
<li><p>箭头函数除外，其他函数都具有<code>arguments</code></p>
</li>
<li><p><code>callee</code>属性，是一个指向<code>arguments</code>对象所在函数的指针。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 阶乘函数</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">factorial</span>(<span class="params">num</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(num &lt;= <span class="number">1</span>)&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">    &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> num * factorial(num-<span class="number">1</span>);	<span class="comment">// 这样会使得 函数逻辑 与 函数名 耦合增加</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 使用callee属性重写</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">factorial</span>(<span class="params">num</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(num &lt;= <span class="number">1</span>)&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">    &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> num * <span class="built_in">arguments</span>.callee(num-<span class="number">1</span>);	<span class="comment">// 这样会使得 函数逻辑 与 函数名 解耦</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(factorial(<span class="number">5</span>));  <span class="comment">// 120</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>在严格模式下：不能访问<code>arugments.callee</code></p>
</blockquote>
</li>
</ul>
<h4 id="10-9-2-this"><a href="#10-9-2-this" class="headerlink" title="10.9.2 this"></a>10.9.2 this</h4><ul>
<li><p><strong>在标准函数中</strong>，<code>this</code>指向把函数当成<code>方法调用</code>的上下文对象。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">color = <span class="string">&#x27;red&#x27;</span>;</span><br><span class="line"><span class="keyword">let</span> o = &#123;</span><br><span class="line">    <span class="attr">color</span>:<span class="string">&#x27;blue&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sayColor</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.color);</span><br><span class="line">&#125;</span><br><span class="line">sayColor();	<span class="comment">// red</span></span><br><span class="line">o.sayColor = sayColor;</span><br><span class="line">o.sayColor();	<span class="comment">// blue</span></span><br></pre></td></tr></table></figure></li>
<li><p><strong>在箭头函数中</strong>，<code>this</code>指向<code>定义箭头函数</code>的上下文。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">color = <span class="string">&#x27;red&#x27;</span>;</span><br><span class="line"><span class="keyword">let</span> o = &#123;</span><br><span class="line">    <span class="attr">color</span>:<span class="string">&#x27;blue&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line">sayColor = <span class="function">()=&gt;</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.color);</span><br><span class="line">&#125;</span><br><span class="line">sayColor();	<span class="comment">// red</span></span><br><span class="line">o.sayColor = sayColor;</span><br><span class="line">o.sayColor();	<span class="comment">// red</span></span><br></pre></td></tr></table></figure></li>
</ul>
<h4 id="10-9-3-caller-与-递归"><a href="#10-9-3-caller-与-递归" class="headerlink" title="10.9.3 caller 与 递归"></a>10.9.3 caller 与 递归</h4><p>该属性引用：调用当前函数的函数。【如果在全局作用域中调用则为null】</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">outer</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    inner();</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">inner</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">arguments</span>.callee.caller);</span><br><span class="line">&#125;</span><br><span class="line">outer();	<span class="comment">// outer()</span></span><br><span class="line">inner();	<span class="comment">// null</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>因为在严格模式下：</p>
<ul>
<li>不能给函数的<code>caller</code>属性赋值；</li>
<li>不能访问<code>arugments.callee</code></li>
</ul>
<p>所以：可以使用<strong>命名函数表达式</strong>来达到目的；</p>
<blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 阶乘函数</span></span><br><span class="line"><span class="keyword">const</span> factorial = (<span class="function"><span class="keyword">function</span> <span class="title">f</span>(<span class="params">num</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(num &lt;= <span class="number">1</span>)&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">    &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> num * f(num -<span class="number">1</span>);	<span class="comment">// 这样会使得 函数逻辑 与 函数名 耦合增加</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br><span class="line"><span class="built_in">console</span>.log(factorial(<span class="number">5</span>));  <span class="comment">// 120</span></span><br></pre></td></tr></table></figure>


</blockquote>
</blockquote>
<h4 id="10-9-4-new-target"><a href="#10-9-4-new-target" class="headerlink" title="10.9.4 new.target"></a>10.9.4 new.target</h4><p>该属性，用于检查函数是否使用<code>new</code>关键字进行构造；</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Plugin</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(<span class="keyword">new</span>.target)&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&quot;The plugin had been installed&quot;</span>);</span><br><span class="line">    &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="string">&quot;Plugin must be install using new&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="10-10-函数属性与方法"><a href="#10-10-函数属性与方法" class="headerlink" title="10.10 函数属性与方法"></a>10.10 函数属性与方法</h3><h4 id="10-10-1-函数的属性"><a href="#10-10-1-函数的属性" class="headerlink" title="10.10.1 函数的属性"></a>10.10.1 函数的属性</h4><ol>
<li>length：保存着函数定义的命名参数的个数</li>
<li>prototype：保存引用类型的原型，里面存着该引用类型所有实例的共享方法</li>
</ol>
<h4 id="10-10-2-函数的方法"><a href="#10-10-2-函数的方法" class="headerlink" title="10.10.2 函数的方法"></a>10.10.2 函数的方法</h4><p>除了<code>toString()</code>、<code>valueOf()</code>等方法之外，还有两个比较重要的方法：</p>
<ol>
<li><p><code>apply()</code>：接收两个参数：一个是函数内部<code>this</code>的指向；另一个是<code>参数数组</code>。</p>
</li>
<li><p><code>call()</code>：接收N个参数：一个是函数内部<code>this</code>的指向；其余的是<code>逐个参数</code>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sum</span>(<span class="params">num1,num2</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(num1 + num2);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">callSum</span>(<span class="params">num1,num2</span>)</span>&#123;</span><br><span class="line">    sum.call(<span class="built_in">this</span>,num1,num2)</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">applySum</span>(<span class="params">num1,num2</span>)</span>&#123;</span><br><span class="line">    sum.apply(<span class="built_in">this</span>,<span class="built_in">arguments</span>)</span><br><span class="line">&#125;</span><br><span class="line">callSum(<span class="number">10</span>,<span class="number">20</span>);		<span class="comment">// 30</span></span><br><span class="line">applySum(<span class="number">10</span>,<span class="number">20</span>);	<span class="comment">// 30</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>在严格模式下，如果没有给<code>this</code>明确的指向，其不会自动指向<code>window</code>，而是会指向<code>undefined</code>。</p>
</blockquote>
</li>
<li><p>ES5中，也提供了一个绑定函数<code>this</code>指向的函数：</p>
<ul>
<li><p><code>bind()</code>：给函数绑定<code>this</code>指向，并<strong>创建</strong>一个新的函数实例。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">color = <span class="string">&#x27;red&#x27;</span>;</span><br><span class="line"><span class="keyword">let</span> o = &#123;</span><br><span class="line">    <span class="attr">color</span>:<span class="string">&#x27;blue&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sayColor</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.color);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> anotherSayColor = sayColor.bind(o);</span><br><span class="line"></span><br><span class="line">sayColor();	<span class="comment">// red</span></span><br><span class="line">anotherSayColor();	<span class="comment">// blue;</span></span><br></pre></td></tr></table></figure></li>
</ul>
</li>
</ol>
<h3 id="10-11-尾调、优化及递归"><a href="#10-11-尾调、优化及递归" class="headerlink" title="10.11 尾调、优化及递归"></a>10.11 尾调、优化及递归</h3><p>ES6中新增了一项<strong>内存管理优化机制</strong>；让JS引擎在满足条件下，可以重用<code>栈帧</code></p>
<p>这项优化是非常使用<code>尾调用的</code>，即：外部函数的返回值是内部函数的返回值。</p>
<h4 id="10-11-1-举个例子"><a href="#10-11-1-举个例子" class="headerlink" title="10.11.1 举个例子"></a>10.11.1 举个例子</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">outerFunction</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> innerFunction();	<span class="comment">// 尾调用</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>在ES6优化之前， 执行这个例子会在内存中发生如下操作。</p>
<p>(1) 执行到<code>outerFunction</code>函数体， 第一个栈帧被推到栈上。</p>
<p>(2) 执行<code>outerFunction</code>函数体， 到return语句。 计算返回值必须先计算<code>innerFunction</code>。</p>
<p>(3) 执行到<code>innerFunction</code>函数体， 第二个栈帧被推到栈上。</p>
<p>(4) 执行<code>innerFunction</code>函数体， 计算其返回值。</p>
<p>(5) 将返回值传回<code>outerFunction</code>， 然后<code>outerFunction</code>再返回值。</p>
<p>(6) 将栈帧弹出栈外。</p>
<p>在ES6优化之后， 执行这个例子会在内存中发生如下操作。</p>
<p>(1) 执行到<code>outerFunction</code>函数体， 第一个栈帧被推到栈上。</p>
<p>(2) 执行<code>outerFunction</code>函数体， 到达<code>return</code>语句。 为求值返回语句， 必须先求值<code>innerFunction</code>。</p>
<p>(3) 引擎发现把第一个栈帧弹出栈外也没问题， 因为<code>innerFunction</code>的返回值也是<code>outerFunction</code>的返回值。</p>
<p>(4) 弹出<code>outerFunction</code>的栈帧。</p>
<p>(5) 执行到<code>innerFunction</code>函数体， 栈帧被推到栈上。</p>
<p>(6) 执行<code>innerFunction</code>函数体， 计算其返回值。</p>
<p>(7) 将<code>innerFunction</code>的栈帧弹出栈外。  </p>
<blockquote>
<p>显然，未优化之前，会多调用一个<code>栈帧</code></p>
</blockquote>
</blockquote>
<h4 id="10-11-2-尾调优化的条件"><a href="#10-11-2-尾调优化的条件" class="headerlink" title="10.11.2 尾调优化的条件"></a>10.11.2 尾调优化的条件</h4><ul>
<li>代码在严格模式下执行</li>
<li>尾调用函数返回后，不再需要执行其他逻辑</li>
<li>尾调用函数不是引用外部函数作用域中自由变量的闭包</li>
</ul>
<blockquote>
<p>举个例子：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&quot;use strict&quot;</span>;</span><br><span class="line"><span class="comment">// 无优化： 尾调用没有返回</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">outerFunction</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    innerFunction();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 无优化： 尾调用没有直接返回</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">outerFunction</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> innerFunctionResult = innerFunction();</span><br><span class="line">    <span class="keyword">return</span> innerFunctionResult;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 无优化： 尾调用返回后必须转型为字符串</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">outerFunction</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> innerFunction().toString();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 无优化： 尾调用是一个闭包</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">outerFunction</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> foo = <span class="string">&#x27;bar&#x27;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">innerFunction</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> foo;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> innerFunction();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 有优化： 栈帧销毁前执行参数计算</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">outerFunction</span>(<span class="params">a, b</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> innerFunction(a + b);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 有优化： 初始返回值不涉及栈帧</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">outerFunction</span>(<span class="params">a, b</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (a &lt; b) &#123;</span><br><span class="line">        <span class="keyword">return</span> a;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> innerFunction(a + b);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//有优化： 两个内部函数都在尾部</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">outerFunction</span>(<span class="params">condition</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> condition ? innerFunctionA() : innerFunctionB();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</blockquote>
<h4 id="10-11-3-对斐波那契数列递归进行尾调优化"><a href="#10-11-3-对斐波那契数列递归进行尾调优化" class="headerlink" title="10.11.3 对斐波那契数列递归进行尾调优化"></a>10.11.3 对斐波那契数列递归进行尾调优化</h4><blockquote>
<p>优化前：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">fb</span>(<span class="params">n</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">if</span>( n&lt;<span class="number">2</span> )&#123;</span><br><span class="line">        <span class="keyword">return</span> n;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> fb(n-<span class="number">1</span>) + fb(n-<span class="number">2</span>);	<span class="comment">// 每次都额外调用两个栈帧，内存复杂度达到2的N次方</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>优化后：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&quot;use strict&quot;</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">fb</span>(<span class="params">n</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> fbPlus(<span class="number">0</span>,<span class="number">1</span>,n);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">fbPlus</span>(<span class="params">a,b,n</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">if</span>( n==<span class="number">0</span> )&#123;</span><br><span class="line">        <span class="keyword">return</span> a;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> fbPlus(b , a+b , n-<span class="number">1</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</blockquote>
<h3 id="10-12-闭包"><a href="#10-12-闭包" class="headerlink" title="10.12 闭包"></a>10.12 闭包</h3><h4 id="10-12-1-什么是闭包？"><a href="#10-12-1-什么是闭包？" class="headerlink" title="10.12.1 什么是闭包？"></a>10.12.1 什么是闭包？</h4><p>闭包：引用了另一个函数作用域中变量的函数；</p>
<p>比如说：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">create</span>(<span class="params">name</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">object</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">let</span> objName = object[name];		<span class="comment">// 内部匿名函数 引用了 外部函数的变量</span></span><br><span class="line">        <span class="keyword">return</span> objName;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>之前在<code>第四章</code>讲过作用域链；这里再次强调一下<strong>函数的作用域链</strong>：</p>
<blockquote>
<p>在函数执行时，每个执行上下文中都会有一个包含其中变量的对象。</p>
<p><code>全局上下文</code>中叫做<code>变量对象</code>，他会在代码执行期间始终存在。</p>
<p><code>函数局部上下文</code>中叫做<code>活动对象</code>，他会在函数执行期间存在。</p>
<p>在定义函数的时候，会创建相应的<code>执行上下文</code>，然后通过复制函数的<code>[[Scope]]</code>来<strong>创建其作用域链</strong>。最后创建函数的<code>活动对象</code>并将其<code>推入</code>作用域链的前端。</p>
<p>在函数执行完毕后，<code>局部活动对象</code>就被销毁了。</p>
</blockquote>
</blockquote>
<p>在闭包中：即在函数（<code>create()</code>）内部定义的函数（<code>匿名函数</code>），会把包含函数（<code>create()</code>）的活动对象添加到自己（<code>匿名函数</code>）的作用域链中。</p>
<img src="https://pic.imgdb.cn/item/6215f7982ab3f51d91900ebd.png" style="zoom: 80%;" />

<p>当<code>create()</code>函数执行完毕后，其<code>执行上下文</code>会被销毁；但是由于<code>匿名函数</code>仍然引用其<code>活动对象</code>。所以<code>create()</code>函数的<code>活动对象</code>仍然留在内存中；直到匿名函数被销毁才跟着销毁。</p>
<blockquote>
<p>所以，在选择使用闭包的时候，需要谨慎思考。</p>
</blockquote>
<h4 id="10-12-2-this对象"><a href="#10-12-2-this对象" class="headerlink" title="10.12.2 this对象"></a>10.12.2 this对象</h4><p>在闭包中，使用<code>this</code>会让代码更加复杂。如果内部函数没有使用箭头函数定义，则<code>this</code>对象会被绑定到<code>执行函数的上下文</code>。</p>
<blockquote>
<p>例子1：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">color = <span class="string">&#x27;red&#x27;</span>;</span><br><span class="line"><span class="keyword">let</span> object = &#123;</span><br><span class="line">    <span class="attr">color</span>:<span class="string">&#x27;blue&#x27;</span>,</span><br><span class="line">    <span class="function"><span class="title">sayColor</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="built_in">this</span>);</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="built_in">this</span>.color);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">object.sayColor()();	<span class="comment">// red</span></span><br></pre></td></tr></table></figure>

<p>执行函数的是<code>objec</code>t，而<code>object</code>则处在<code>全局上下文中</code>，所以这时候的<code>this</code>被绑定到<code>全局上下文中</code>。</p>
<blockquote>
<p>如何使得内部函数（<code>匿名函数</code>）访问外部函数（<code>sayColor</code>）的<code>this</code>呢？</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">color = <span class="string">&#x27;red&#x27;</span>;</span><br><span class="line"><span class="keyword">let</span> object = &#123;</span><br><span class="line">    <span class="attr">color</span>:<span class="string">&#x27;blue&#x27;</span>,</span><br><span class="line">    <span class="function"><span class="title">sayColor</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="keyword">let</span> that = <span class="built_in">this</span>;</span><br><span class="line">        <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">            <span class="built_in">console</span>.log(that);		<span class="comment">// &#123; color: &#x27;blue&#x27;, sayColor: [Function: sayColor] &#125;</span></span><br><span class="line">            <span class="built_in">console</span>.log(that.color);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">object.sayColor()();	<span class="comment">// blue</span></span><br></pre></td></tr></table></figure>

<p>除<code>this</code>之外，<code>arguments</code>也不能被内部函数所访问。</p>
</blockquote>
</blockquote>
<h4 id="10-12-3-内存泄漏"><a href="#10-12-3-内存泄漏" class="headerlink" title="10.12.3 内存泄漏"></a>10.12.3 内存泄漏</h4><p>因为闭包的关系，所以外部函数的<code>活动对象</code>的引用计数永远不为0，导致内存泄漏。</p>
<h3 id="10-13-IIFE"><a href="#10-13-IIFE" class="headerlink" title="10.13 IIFE"></a>10.13 IIFE</h3><p>立即调用的匿名又称作<strong>立即调用的函数表达式（IIFE, Immediately Invoked Function Expression）</strong></p>
<blockquote>
<p>在ES5中，没有块级作用域；可以使用IIFE来模拟块级作用域</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">var</span> i=<span class="number">0</span> ; i&lt;<span class="number">5</span> ; i++)&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(i); <span class="comment">// 0 1 2 3 4</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;)(); </span><br><span class="line"><span class="built_in">console</span>.log(i);     <span class="comment">// i is not defined</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>这样看可以防止闭包导致的内存问题，因为不存在对这个匿名函数的引用；</p>
</blockquote>
<p>在ES6中，可以这样定义</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    <span class="keyword">let</span> i;</span><br><span class="line">    <span class="keyword">for</span>(i=<span class="number">0</span> ; i&lt;<span class="number">5</span> ; i++)&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(i);	<span class="comment">// 0 1 2 3 4</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">let</span> i=<span class="number">0</span> ; i&lt;<span class="number">5</span> ; i++)&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(i);	<span class="comment">// 0 1 2 3 4</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(i);	<span class="comment">// i is not defined</span></span><br></pre></td></tr></table></figure>
</blockquote>
<blockquote>
<p>块级作用域有这样的用处：给div添加点击事件，每次点击都会显示其索引</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span>(<span class="keyword">let</span> i=<span class="number">0</span> ; i&lt;divs.length ; i++)&#123;</span><br><span class="line">    divs[i].addEventListener(<span class="string">&#x27;click&#x27;</span>,<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(i);</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</blockquote>
<h3 id="10-14-私有变量"><a href="#10-14-私有变量" class="headerlink" title="10.14 私有变量"></a>10.14 私有变量</h3><p>严格来讲，JavaScript中没有私有变量，但是私有变量的概念；可以通过各种方法实现变量私有化。</p>
<h4 id="10-14-1-特权方法实现私有变量"><a href="#10-14-1-特权方法实现私有变量" class="headerlink" title="10.14.1 特权方法实现私有变量"></a>10.14.1 特权方法实现私有变量</h4><blockquote>
<p>一个函数中创建一个<code>闭包</code>，则这个<code>闭包</code>能通过其作用域链访问函数中的变量、方法；</p>
</blockquote>
<p><strong>特权方法</strong>是能够<strong>访问函数私有变量、方法</strong>的<code>公有方法</code>：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Person</span>(<span class="params">name</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">let</span> _name = name;	<span class="comment">// 私有变量</span></span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 特权方法</span></span><br><span class="line">    <span class="built_in">this</span>.getName = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;	<span class="comment">// 公有方法</span></span><br><span class="line">        <span class="keyword">return</span> _name;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">this</span>.setName = <span class="function"><span class="keyword">function</span>(<span class="params">value</span>)</span>&#123;	<span class="comment">// 公有方法</span></span><br><span class="line">        _name = value</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>显然，这就是<code>构造函数模式</code>，其缺点就是<strong>每个实例都会重新创建一遍新方法</strong>；使用<code>静态私有变量</code>实现特权方法可以避免这个问题</p>
<h4 id="10-14-2-静态私有变量"><a href="#10-14-2-静态私有变量" class="headerlink" title="10.14.2 静态私有变量"></a>10.14.2 静态私有变量</h4><ul>
<li>通过闭包的方法，形成私有变量；</li>
<li>通过无关键字声明对象，形成全局变量；</li>
<li>通过给上面的全局变量的原型定义方法，达到特权方法所有实例共享的目的；</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="comment">// 私有变量</span></span><br><span class="line">    <span class="keyword">let</span> _name = <span class="string">&#x27;defaultName&#x27;</span>;</span><br><span class="line">    <span class="comment">// 构造函数</span></span><br><span class="line">    Person = <span class="function"><span class="keyword">function</span>(<span class="params">name</span>)</span>&#123;</span><br><span class="line">        _name = name;</span><br><span class="line">    &#125;;</span><br><span class="line">    <span class="comment">// 公有和特权方法</span></span><br><span class="line">    Person.prototype.getName = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> _name;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)();</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> person = <span class="keyword">new</span> Person(<span class="string">&#x27;zyzc&#x27;</span>);</span><br><span class="line"><span class="built_in">console</span>.log(person.getName());		<span class="comment">// zyzc</span></span><br><span class="line"><span class="built_in">console</span>.log(_name);		<span class="comment">// _name is not defined</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p><strong>注意：</strong>使用闭包和私有变量，会使得作用域链边长，导致变量查找的所需时间边长。</p>
</blockquote>
<h4 id="10-14-3-模块模式"><a href="#10-14-3-模块模式" class="headerlink" title="10.14.3 模块模式"></a>10.14.3 模块模式</h4><p>模块模式：在一个单例对象上实现了相同的隔离和封装。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> BaseComponent = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;&#125;;	<span class="comment">// 组件1</span></span><br><span class="line"><span class="keyword">let</span> application = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">let</span> components = <span class="keyword">new</span> <span class="built_in">Array</span>();		<span class="comment">// 用于存储组件</span></span><br><span class="line">    components.push(<span class="keyword">new</span> BaseComponent());	<span class="comment">// 初始化</span></span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 公共接口</span></span><br><span class="line">    <span class="keyword">return</span>&#123;</span><br><span class="line">        <span class="function"><span class="title">getComponent</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">            <span class="keyword">return</span> components.length;</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="function"><span class="title">registerComponent</span>(<span class="params">component</span>)</span>&#123;</span><br><span class="line">            <span class="keyword">if</span>(<span class="keyword">typeof</span> component == <span class="string">&#x27;object&#x27;</span>)&#123;</span><br><span class="line">                components.push(component);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;();</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(application.getComponent());	<span class="comment">// 1</span></span><br><span class="line">application.registerComponent(<span class="keyword">new</span> BaseComponent());</span><br><span class="line"><span class="built_in">console</span>.log(application.getComponent());	<span class="comment">// 2</span></span><br></pre></td></tr></table></figure>



<h4 id="10-14-4-增强的模块模式"><a href="#10-14-4-增强的模块模式" class="headerlink" title="10.14.4 增强的模块模式"></a>10.14.4 增强的模块模式</h4><p>结合模块模式，返回对象之前，对对象进行<code>升级、武装</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> Person = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">let</span> name;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">sayHi</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;hi&#x27;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">        name,</span><br><span class="line">        sayHi</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">let</span> Solider = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="comment">// 私有属性</span></span><br><span class="line">    <span class="keyword">let</span> weapons = [<span class="string">&#x27;knife&#x27;</span>,<span class="string">&#x27;tank&#x27;</span>,<span class="string">&#x27;guns&#x27;</span>];</span><br><span class="line">    <span class="comment">// 私有方法</span></span><br><span class="line">    <span class="keyword">let</span> shot = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;I am shooting&#x27;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">let</span> person = <span class="keyword">new</span> Person();	<span class="comment">// 创建一个普通的人</span></span><br><span class="line">    </span><br><span class="line">    person.shot = shot;		<span class="comment">// 增强方法</span></span><br><span class="line">    person.weapons = weapons;	<span class="comment">// 增强属性</span></span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> person;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> soliderA = <span class="keyword">new</span> Solider(); </span><br><span class="line">soliderA.sayHi();               <span class="comment">// 既有未增强前的个性</span></span><br><span class="line">soliderA.shot();                <span class="comment">// 又有增强后的特性</span></span><br><span class="line"><span class="built_in">console</span>.log(soliderA.weapons);</span><br></pre></td></tr></table></figure>



<h4 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h4><ul>
<li>函数的有如下几种表达形式<ul>
<li>函数表达式</li>
<li>函数声明式</li>
<li>匿名函数</li>
<li>箭头函数</li>
</ul>
</li>
<li>函数的参数具有非常高的<code>灵活性</code></li>
<li>函数的内部暴露了很多对象和属性：<code>this</code>、<code>arguments</code>、<code>new.target</code>、<code>callee</code>、<code>caller</code></li>
<li>可以通过函数内部暴露的对象、属性，获取很多信息</li>
<li><code>JavaScript</code>引擎可以优化符合尾调条件的函数，可以节省栈空间。</li>
<li>要谨慎使用<code>闭包</code></li>
<li><code>JavaScript</code>中虽然<strong>没有私有变量的概念</strong>，但是可以通过一些模式，实现私有变量。</li>
<li>可以通过<code>特权方法</code>访问私有变量、方法；</li>
<li><code>特权方法</code>可以使用构造函数或原型模式，通过自定义类型实现；也可以通过<code>模块模式</code>或<code>增强模块模式</code>在单例对象上实现。</li>
</ul>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>Copyright： </strong>
          
          Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://example.com/2022/02/23/JavaScript%E5%AD%A6%E4%B9%A0/%E3%80%8AJavaScript%E9%AB%98%E7%BA%A7%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E3%80%8B-%20%E7%AC%AC%E5%8D%81%E7%AB%A0%EF%BC%9A%E5%87%BD%E6%95%B0/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/JavaScript/" rel="tag">JavaScript</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2022/02/25/JavaScript%E5%AD%A6%E4%B9%A0/%E3%80%8AJavaScript%E9%AB%98%E7%BA%A7%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E3%80%8B-%20%E7%AC%AC%E5%8D%81%E4%B8%80%E7%AB%A0%EF%BC%9A%E6%9C%9F%E7%BA%A6/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            《JavaScript高级程序设计》- 第十一章：期约
          
        </div>
      </a>
    
    
      <a href="/2022/02/22/JavaScript%E5%AD%A6%E4%B9%A0/%E3%80%8AJavaScript%E9%AB%98%E7%BA%A7%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E3%80%8B-%20%E7%AC%AC%E4%B9%9D%E7%AB%A0%EF%BC%9A%E4%BB%A3%E7%90%86%E4%B8%8E%E5%8F%8D%E5%B0%84/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">《JavaScript高级程序设计》- 第九章：代理与反射</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "jeb2pvxjdeJQOj5OG3AUavGv-gzGzoHsz",
    app_key: "6YlB9tQJTstHMM8GOwFu4uyY",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
   
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2022
        <i class="ri-heart-fill heart_icon"></i> 子与子乘
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>Visitors:<span id="busuanzi_value_site_uv"></span></span>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>Views:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
      </li>
    </ul>
  </div>
</footer>    
    </main>
    <div class="float_btns">
      <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

    </div>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="欢迎"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/friends">友链</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i></p>
  <div class="reward-box">
    
    
  </div>
</div>
    
<script src="/js/jquery-3.6.0.min.js"></script>
 
<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->
 
<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: ".tocbot",
    contentSelector: ".article-entry",
    headingSelector: "h1, h2, h3, h4, h5, h6",
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: "main",
    positionFixedSelector: ".tocbot",
    positionFixedClass: "is-position-fixed",
    fixedSidebarOffset: "auto",
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css"
/>
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->
 <!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script> 
<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->
 
<script src="/js/busuanzi-2.3.pure.min.js"></script>
 
<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->
 
<link rel="stylesheet" href="/css/clipboard.css">
 <script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>
 
<!-- CanvasBackground -->

<script>
  if (window.mermaid) {
    mermaid.initialize({ theme: "forest" });
  }
</script>


    
    

  </div>
</body>

</html>